﻿# -*- coding:utf-8 -*-
import datetime
from django.conf import settings
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.http import HttpResponseForbidden
from django.http import Http404
from django.core.urlresolvers import reverse
from django.template import RequestContext, Context

from models import Device, Equipment, Exhibition, History
from forms import DeviceNewForm, DeviceMoveToExhibitionForm, DeviceMoveToExpositionForm, DeviceMoveToRepairForm, DeviceMoveToStorageForm

def index(request):

    devices = Device.objects.select_related().all()
    devices_all = devices.count()
    devices_str = devices.filter(location='str').count()
    devices_rpr = devices.filter(location='rpr').count()
    devices_exp = devices.filter(location='exp').count()
    devices_exh = devices.filter(location='exh').count()
    now_date = datetime.date.today()
    exhibition_open = Exhibition.objects.filter(date_open__lte=now_date, date_close__gte=now_date)
    exhibition_closed = Exhibition.objects.filter(date_close__lt=now_date)
    historys = History.objects.select_related().all().order_by('-date')
    
    context = Context({
      'devices': devices,
      'devices_str':devices_str,
      'devices_rpr':devices_rpr,
      'devices_exp':devices_exp,
      'devices_exh':devices_exh,
      'devices_all':devices_all,
      'exhibition_open':exhibition_open,
      'exhibition_closed':exhibition_closed,
      'historys':historys,
    })
    return render_to_response('expdev/index.html', context, context_instance=RequestContext(request))



def device_list(request):
    p = request.GET.get('par', 'all')
    if p == 'all':
        devices = Device.objects.select_related().all()
        filter_loc='all'
    else:  
        devices = Device.objects.select_related().filter(location=p)
        filter_loc=p

    context = Context({
      'devices': devices,
      'filter_loc':filter_loc,
    })
    return render_to_response('expdev/device_list.html', context, context_instance=RequestContext(request))



def device_property(request, device_id):    
    device = get_object_or_404(Device, id=device_id)
    historys = History.objects.filter(device__id=device_id)
    context = Context({
      'device': device,
      'historys':historys,
    })
    return render_to_response('expdev/device_property.html', context, context_instance=RequestContext(request))
    
    
def device_new(request): 
    if request.method == 'POST':
        form = DeviceNewForm( request.POST)
        if form.is_valid():
            devinst = form.save(commit=False)
            devinst.save()
            h = History(device=devinst, action='Device Created', comment='', user=request.user)
            h.save();
            return HttpResponseRedirect(reverse('ktit.expdev.views.device_property', args=[devinst.id]))
    else:
        form = DeviceNewForm()

    context = Context({
      'form': form,
    })
    return render_to_response('expdev/device_new.html', context, context_instance=RequestContext(request))


def device_moveto(request, device_id):

    id = int(request.GET.get('id', 0)) 


    context = Context({
      #'form': form,
    })
    return render_to_response('expdev/device_moveto_storage.html', context, context_instance=RequestContext(request))



def device_moveto_storage(request, device_id):
    device = get_object_or_404(Device, id=device_id)
    if request.method == 'POST':
        form = DeviceMoveToStorageForm(request.POST)
        if form.is_valid():
            comment = form.cleaned_data['comment']
            device.location = 'str'
            device.verbose_location = 'Склад'
            device.exhibition = None
            device.save()
            h = History(device=device, action='Перемещено на склад', comment=comment, user=request.user) 
            h.save()
            return HttpResponseRedirect(reverse('ktit.expdev.views.device_property', args=[device_id]))
    else:
        form = DeviceMoveToStorageForm()
    context = Context({
      'form': form,
    })
    return render_to_response('expdev/device_moveto_storage.html', context, context_instance=RequestContext(request))



def device_moveto_repair(request, device_id):
    device = get_object_or_404(Device, id=device_id)
    if request.method == 'POST':
        form = DeviceMoveToRepairForm(request.POST)
        if form.is_valid():
            comment = form.cleaned_data['comment']
            device.location = 'rpr'
            device.verbose_location = 'Ремонт'
            device.exhibition = None
            device.save()
            h = History(device=device, action='Перемещено в ремонт', comment=comment, user=request.user) 
            h.save()        
            return HttpResponseRedirect(reverse('ktit.expdev.views.device_property', args=[device_id]))
    else:
        form = DeviceMoveToRepairForm()
    context = Context({
      'form': form,
    })
    return render_to_response('expdev/device_moveto_repair.html', context, context_instance=RequestContext(request))



def device_moveto_exhibition(request, device_id):
    device = get_object_or_404(Device, id=device_id)
    if request.method == 'POST':
        form = DeviceMoveToExhibitionForm(request.POST)
        if form.is_valid():
            comment = form.cleaned_data['comment']
            exhibition = form.cleaned_data['exhibition']
            device.location = 'exh'
            device.verbose_location = 'Выставка'
            device.exhibition = exhibition
            device.save()
            h = History(device=device, action='Перемещено на временную выставку', comment=comment, user=request.user) 
            h.save()  
            return HttpResponseRedirect(reverse('ktit.expdev.views.device_property', args=[device_id]))
    else:
        form = DeviceMoveToExhibitionForm()
    context = Context({
      'form': form,
    })
    return render_to_response('expdev/device_moveto_exhibition.html', context, context_instance=RequestContext(request))



def device_moveto_exposition(request, device_id):
    device = get_object_or_404(Device, id=device_id) 
    if request.method == 'POST':
        form = DeviceMoveToExpositionForm(request.POST)
        if form.is_valid():
            comment = form.cleaned_data['comment']
            exposition = form.cleaned_data['exposition']
            device.location = 'exp'
            device.verbose_location = 'Экспозиция'
            device.exhibition = exposition
            device.save()
            h = History(device=device, action='Перемещено на постоянную экспозицию', comment=comment, user=request.user) 
            h.save()  
            return HttpResponseRedirect(reverse('ktit.expdev.views.device_property', args=[device_id]))
    else:
        form = DeviceMoveToExpositionForm()
    context = Context({
      'form': form,
    })
    return render_to_response('expdev/device_moveto_exposition.html', context, context_instance=RequestContext(request))





